import * as fs from 'fs';
import * as path from 'path';
import archiver from 'archiver';
import axios from 'axios';
import { app } from 'electron';
// 修改前
// import { apiBaseUrl } from '../../config.js';
// 修改后
import { apiBaseUrl } from '../config';

export interface SyncResult {
  success: boolean;
  message: string;
  data?: any;
}

export class SyncService {
  private readonly userDataPath: string;
  private readonly configPath: string;
  private readonly tempDir: string;

  constructor() {
    this.userDataPath = process.env.NODE_ENV === 'development'
      ? path.join(__dirname, '../../browser-instances')
      : path.join(process.resourcesPath, 'browser-instances');
    
    this.configPath = process.env.NODE_ENV === 'development'
      ? path.join(__dirname, '../../browser-configs.json')
      : path.join(process.resourcesPath, 'browser-configs.json');
    
    this.tempDir = path.join(app.getPath('temp'), 'browser-sync');
  }

  /**
   * 压缩用户配置文件
   */
  private async createBackupArchive(): Promise<string> {
    return new Promise((resolve, reject) => {
      const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
      const archivePath = path.join(this.tempDir, `browser-backup-${timestamp}.zip`);
      
      // 确保临时目录存在
      if (!fs.existsSync(this.tempDir)) {
        fs.mkdirSync(this.tempDir, { recursive: true });
      }

      const output = fs.createWriteStream(archivePath);
      const archive = archiver('zip', {
        zlib: { level: 9 } // 最高压缩级别
      });

      output.on('close', () => {
        console.log(`Archive created: ${archivePath} (${archive.pointer()} bytes)`);
        resolve(archivePath);
      });

      archive.on('error', (err: any) => {
        reject(err);
      });

      archive.pipe(output);

      // 添加配置文件
      if (fs.existsSync(this.configPath)) {
        archive.file(this.configPath, { name: 'browser-configs.json' });
      }

      // 获取所有实例目录名
      let instanceDirs: string[] = [];
      if (fs.existsSync(this.userDataPath)) {
        instanceDirs = fs.readdirSync(this.userDataPath, { withFileTypes: true })
          .filter(dirent => dirent.isDirectory())
          .map(dirent => dirent.name);
      }

      for (const instanceId of instanceDirs) {
        const instancePath = path.join(this.userDataPath, instanceId);
        const localStatePath = path.join(instancePath, 'Local State');
        const networkDirPath = path.join(instancePath, 'Default', 'Network');

        // 添加 Local State 文件
        if (fs.existsSync(localStatePath)) {
          archive.file(localStatePath, { name: path.join('browser-instances', instanceId, 'Local State') });
        }

        // 添加 Network 目录
        if (fs.existsSync(networkDirPath)) {
          archive.directory(networkDirPath, path.join('browser-instances', instanceId, 'Default', 'Network'));
        }
      }

      // // 添加用户数据目录
      // if (fs.existsSync(this.userDataPath)) {
      //   archive.directory(this.userDataPath, 'browser-instances');
      // }

      archive.finalize();
    });
  }

  /**
   * 解压备份文件
   */
  private async extractBackupArchive(archivePath: string): Promise<void> {
    return new Promise((resolve, reject) => {
      const extract = require('extract-zip');
      
      extract(archivePath, { dir: this.tempDir })
        .then(() => {
          console.log('Archive extracted successfully');
          resolve();
        })
        .catch((err: any) => {
          reject(err);
        });
    });
  }

  /**
   * 上传备份到API
   */
  async uploadBackup(userId: string, token: string): Promise<SyncResult> {
    try {
      console.log('Creating backup archive...');
      const archivePath = await this.createBackupArchive();

      console.log('Uploading backup to API...');
      
      // 使用 FormData 的正确方式
      const FormData = require('form-data');
      const formData = new FormData();
      formData.append('backup', fs.createReadStream(archivePath));
      formData.append('userId', userId);
      formData.append('timestamp', new Date().toISOString());

      const response = await axios.post(
        `${apiBaseUrl}/sync/upload`,
        formData,
        {
          headers: {
            'Authorization': `Bearer ${token}`,
            ...formData.getHeaders()
          },
          timeout: 30000 // 30秒超时
        }
      );

      // 清理临时文件
      fs.unlinkSync(archivePath);

      return {
        success: true,
        message: '备份上传成功',
        data: response.data
      };
    } catch (error) {
      console.error('Upload backup failed:', error);
      return {
        success: false,
        message: error instanceof Error ? error.message : '备份上传失败'
      };
    }
  }

  /**
   * 从API下载备份
   */
  async downloadBackup(userId: string, token: string): Promise<SyncResult> {
    try {
      console.log('Downloading backup from API...');
      console.log(apiBaseUrl)
      const response = await axios.get(
        `${apiBaseUrl}/sync/download/${userId}`,
        {
          headers: {
            'Authorization': `Bearer ${token}`
          },
          responseType: 'stream',
          timeout: 30000
        }
      );

      const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
      const archivePath = path.join(this.tempDir, `browser-backup-${timestamp}.zip`);
      
      // 确保临时目录存在
      if (!fs.existsSync(this.tempDir)) {
        fs.mkdirSync(this.tempDir, { recursive: true });
      }

      const writer = fs.createWriteStream(archivePath);
      response.data.pipe(writer);

      return new Promise((resolve) => {
        writer.on('finish', async () => {
          try {
            console.log('Backup downloaded, extracting...');
            await this.extractBackupArchive(archivePath);
            
            // 恢复配置文件
            const extractedConfigPath = path.join(this.tempDir, 'browser-configs.json');
            if (fs.existsSync(extractedConfigPath)) {
              fs.copyFileSync(extractedConfigPath, this.configPath);
              console.log('Config file restored');
            }

            // 恢复用户数据目录
            const extractedUserDataPath = path.join(this.tempDir, 'browser-instances');
            if (fs.existsSync(extractedUserDataPath)) {
              // 删除现有用户数据目录
              if (fs.existsSync(this.userDataPath)) {
                fs.rmSync(this.userDataPath, { recursive: true, force: true });
              }
              // 复制新的用户数据目录
              fs.cpSync(extractedUserDataPath, this.userDataPath, { recursive: true });
              console.log('User data directory restored');
            }

            // 清理临时文件
            fs.rmSync(this.tempDir, { recursive: true, force: true });

            resolve({
              success: true,
              message: '备份恢复成功'
            });
          } catch (error) {
            resolve({
              success: false,
              message: error instanceof Error ? error.message : '备份恢复失败'
            });
          }
        });

        writer.on('error', (error) => {
          resolve({
            success: false,
            message: error.message
          });
        });
      });
    } catch (error) {
      console.error('Download backup failed:', error);
      return {
        success: false,
        message: error instanceof Error ? error.message : '备份下载失败'
      };
    }
  }

  /**
   * 检查是否有可用的备份
   */
  async checkBackup(userId: string, token: string): Promise<SyncResult> {
    try {
      const response = await axios.get(
        `${apiBaseUrl}/sync/check/${userId}`,
        {
          headers: {
            'Authorization': `Bearer ${token}`
          },
          timeout: 10000
        }
      );

      return {
        success: true,
        message: '检查备份状态成功',
        data: response.data
      };
    } catch (error) {
      console.error('Check backup failed:', error);
      return {
        success: false,
        message: error instanceof Error ? error.message : '检查备份状态失败'
      };
    }
  }
}

export const syncService = new SyncService();